package com.wll.flutter.asr_plugin;

import androidx.annotation.Nullable;

import io.flutter.Log;
import io.flutter.plugin.common.MethodChannel;

/**
 * created by detachment on 2020/10/28
 */
public class ResultStateful implements MethodChannel.Result {
    private static final String TAG = "ResultStateful";
    private MethodChannel.Result result;
    private boolean called;

    public static ResultStateful of(MethodChannel.Result result) {
        return new ResultStateful(result);
    }

    private ResultStateful(MethodChannel.Result result) {
        this.result = result;
    }

    @Override
    public void success(@Nullable Object result) {
        if (called) {
            printError();
            return;
        }
        called = true;
        if (result != null) {
            this.result.success(result);
            Log.w("ResultStateful success:", result.toString());
        }
    }

    @Override
    public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
        if (called) {
            printError();
            return;
        }
        called = true;
        this.result.error(errorCode, errorMessage, errorDetails);
        Log.w("ResultStateful error:", " errorCode:" + errorCode
                + " errorMessage:" + errorMessage
                + " errorDetails:" + (errorDetails != null ? errorDetails.toString() : ""));
    }

    @Override
    public void notImplemented() {
        if (called) {
            printError();
            return;
        }
        called = true;
        this.result.notImplemented();
    }

    private void printError() {
        Log.e(TAG, "error: result called");
    }
}
